class CivilWarApp {
    constructor() {
        this.apiBase = 'http://localhost:5000/api';
        this.states = {};
        this.currentTurn = 0;
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadStates();
    }

    bindEvents() {
        document.getElementById('nextTurnBtn').addEventListener('click', () => this.nextTurn());
        document.getElementById('resetBtn').addEventListener('click', () => this.reset());
    }

    async loadStates() {
        try {
            const response = await fetch(`${this.apiBase}/state`);
            const data = await response.json();
            this.updateUI(data);
        } catch (error) {
            console.error('加载状态失败:', error);
            this.showError('无法连接到服务器，请确保后端正在运行');
        }
    }

    async nextTurn() {
        try {
            document.getElementById('nextTurnBtn').disabled = true;
            const response = await fetch(`${this.apiBase}/next_turn`, {
                method: 'POST'
            });
            const data = await response.json();
            this.updateUI(data);
            document.getElementById('nextTurnBtn').disabled = false;
        } catch (error) {
            console.error('下一回合失败:', error);
            document.getElementById('nextTurnBtn').disabled = false;
        }
    }

    async reset() {
        try {
            const response = await fetch(`${this.apiBase}/reset`, {
                method: 'POST'
            });
            await response.json();
            this.loadStates();
            document.getElementById('stateInfo').style.display = 'none';
        } catch (error) {
            console.error('重置失败:', error);
        }
    }

    updateUI(data) {
        this.states = data.states;
        this.currentTurn = data.turn;
        
        document.getElementById('turnCounter').textContent = this.currentTurn;
        this.renderMap();
        this.renderLogs(data.logs);
    }

    renderMap() {
        const mapContainer = document.getElementById('usMap');
        mapContainer.innerHTML = '';

        Object.entries(this.states).forEach(([name, state]) => {
            const stateDiv = document.createElement('div');
            stateDiv.className = 'state';
            stateDiv.dataset.stateName = name;
            
            const color = this.getStateColor(state);
            stateDiv.style.backgroundColor = color;

            stateDiv.innerHTML = `
                <div class="state-name">${state.abbreviation}</div>
                <div class="state-troops">${this.formatNumber(state.troops)}</div>
                <div class="state-territories">${state.territories.length}州</div>
            `;

            stateDiv.addEventListener('click', () => this.showStateDetails(name));
            mapContainer.appendChild(stateDiv);
        });
    }

    getStateColor(state) {
        if (state.wars.length > 0) {
            return 'rgba(255, 107, 107, 0.3)'; // 战争状态 - 红色
        } else if (state.alliances.length > 0) {
            return 'rgba(255, 217, 61, 0.3)'; // 联盟状态 - 黄色
        } else {
            return 'rgba(76, 175, 80, 0.3)'; // 和平状态 - 绿色
        }
    }

    renderLogs(logs) {
        const logsContainer = document.getElementById('logs');
        logsContainer.innerHTML = '';

        logs.forEach(log => {
            const logDiv = document.createElement('div');
            logDiv.className = 'log-entry';
            
            if (log.includes('宣战')) {
                logDiv.classList.add('war');
            } else if (log.includes('和平') || log.includes('求和')) {
                logDiv.classList.add('peace');
            } else if (log.includes('联盟')) {
                logDiv.classList.add('alliance');
            }

            logDiv.textContent = log;
            logsContainer.appendChild(logDiv);
        });

        // 滚动到最新日志
        logsContainer.scrollTop = logsContainer.scrollHeight;
    }

    showStateDetails(stateName) {
        const state = this.states[stateName];
        const stateInfo = document.getElementById('stateInfo');
        const stateDetails = document.getElementById('stateDetails');

        stateDetails.innerHTML = `
            <h4>${state.name} (${state.abbreviation})</h4>
            <p><strong>兵力:</strong> ${this.formatNumber(state.troops)}</p>
            <p><strong>控制州数:</strong> ${state.territories.length}</p>
            
            <h4>外交关系</h4>
            <ul>
                <li><strong>战争状态:</strong> ${state.wars.length > 0 ? state.wars.join(', ') : '无'}</li>
                <li><strong>联盟:</strong> ${state.alliances.length > 0 ? state.alliances.join(', ') : '无'}</li>
            </ul>
            
            <h4>控制领土</h4>
            <ul>
                ${state.territories.map(t => `<li>${t}</li>`).join('')}
            </ul>
        `;

        stateInfo.style.display = 'block';
    }

    formatNumber(num) {
        return num.toLocaleString();
    }

    showError(message) {
        const logsContainer = document.getElementById('logs');
        const errorDiv = document.createElement('div');
        errorDiv.className = 'log-entry war';
        errorDiv.textContent = `错误: ${message}`;
        logsContainer.appendChild(errorDiv);
    }
}

// 启动应用
document.addEventListener('DOMContentLoaded', () => {
    new CivilWarApp();
});
